<template>
  <view>
    <!-- 作业票验收 -->
    <view class="bg-white page-view">
      <uni-forms ref="form" :modelValue="formData" :rules="rules" labelWidth="70vw" labelPosition="top">
        <view class="hidden-title">信息填写</view>
        <view class="background-white" style="padding-left: 30rpx; margin-bottom: 30rpx; margin-top: 30rpx">
          <CuRadioGroup v-model="formData.acceptanceInfo.type" :list="acceptList" class="pause-radio__group" />
        </view>

        <!-- 完工验收 -->
        <template v-if="formData.acceptanceInfo.type === 1">
          <view class="background-white" style="padding-left: 30rpx; margin-bottom: 30rpx">
            <uni-data-checkbox
              v-model="formData.acceptanceInfo.acceptInfo"
              multiple
              :localdata="finishList"
              @change="changeFinish"
              :map="{ value: 'description', text: 'description' }"
            ></uni-data-checkbox>
          </view>
          <view
            class="background-white"
            style="padding-left: 30rpx; margin-bottom: 30rpx; display: flex; flex-wrap: wrap"
          >
            <image-upload
              v-for="(item, index) in formData.acceptanceList"
              :key="index"
              :limit="1"
              state="edit"
              :imageUrl="item.pictUrl"
              @change="imageOnChange($event, item)"
            ></image-upload>
          </view>
        </template>

        <!-- 未完工作业结束 -->
        <template v-if="formData.acceptanceInfo.type === 2">
          <view class="background-white" style="padding-left: 30rpx; margin-bottom: 30rpx">
            <CuRadioGroup
              isColumn
              v-model="formData.acceptanceInfo.acceptInfo"
              :props="{ value: 'description', label: 'description' }"
              :list="notfinishList"
              @change="changeNotFinish"
            />
          </view>
          <view class="background-white">
            <uni-forms-item style="padding-left: 30rpx" name="acceptanceInfo.otherDescription" label="其他说明">
              <textarea
                v-model="formData.acceptanceInfo.otherDescription"
                :disabled="formData.acceptanceInfo.acceptInfo != '其他原因'"
                class="text-area"
                placeholder="其它说明"
                placeholder-class="form-placeholder__style"
                maxlength="50"
              />
            </uni-forms-item>
          </view>
        </template>

        <view class="background-white">
          <uni-forms-item style="padding-left: 30rpx; margin-top: 30rpx" name="reviewDescription" label="验收意见说明">
            <textarea
              v-model="formData.reviewDescription"
              class="text-area"
              placeholder="简要说明验收意见"
              placeholder-class="form-placeholder__style"
              maxlength="50"
            />
          </uni-forms-item>
        </view>

        <view v-if="workType === specialWorkTypeEnum.LIFTING" class="background-white" style="padding: 0 30rpx">
          <uni-forms-item :name="['acceptanceFile', 'safeCheckTable']" label="起重吊装作业专项安全检查表">
            <image-upload
              :imageUrl="formData.acceptanceFile.safeCheckTable"
              state="edit"
              :limit="3"
              @change="imageChange($event, 'safeCheckTable')"
            />
          </uni-forms-item>
        </view>

        <view v-if="workType === specialWorkTypeEnum.MAINTENANCE" class="background-white" style="padding: 0 30rpx">
          <uni-forms-item :name="['acceptanceFile', 'acceptanceFile']" label="设备检维修作业(交付验收)单">
            <image-upload
              :imageUrl="formData.acceptanceFile.acceptanceFile"
              state="edit"
              :limit="3"
              @change="imageChange($event, 'acceptanceFile')"
            />
          </uni-forms-item>
        </view>

        <view class="background-white" style="padding: 0 30rpx">
          <uni-forms-item :name="['acceptanceFile', 'otherFile']" label="其他附件">
            <image-upload
              v-model="formData.acceptanceFile.otherFile"
              :imageUrl="formData.acceptanceFile.otherFile"
              state="edit"
              :limit="3"
              @change="imageChange($event, 'otherFile')"
            />
          </uni-forms-item>
        </view>

        <view class="background-white" style="padding: 0 30rpx">
          <view v-if="allowMultiSign == 1" class="signature-title">
            <text class="text-error">*</text>
            多人签名(至少添加监护人、作业负责人两人签名)
          </view>
          <Signature
            ref="signature"
            v-model="formData.reviewerSignatures"
            auto-upload
            :allow-multi-sign="allowMultiSign"
            :review-result="formData.reviewResult"
            @success="onSignatureSuccess"
          />
        </view>
      </uni-forms>
      <view class="submit_btn">
        <button class="u-button block" @click="handleSubmit">确定</button>
      </view>
    </view>
  </view>
</template>

<script>
import Signature from '@/pages/jobSlip/components/ContinueSign.vue'
import { saveTicketInspect } from '@/api/spw/ticketInspect.js'
import CuRadioGroup from '@/components/cu-radio-group/cu-radio-group.vue'
import { getDicts } from '@/api/system/dict.js'
import { getCurrentInspectDetail, getAcceptanceConfig, getUnAcceptanceConfig } from '@/api/spw/ticketInspect.js'
import { actNodePermissionEnum, signatureTypeEnum, specialWorkTypeEnum } from '@/utils/constant.js'
import ImageUpload from '@/components/image-upload/index.vue'

export default {
  components: {
    Signature,
    CuRadioGroup,
    ImageUpload
  },
  async onLoad(option) {
    this.getDicts()

    const { nodeTaskId, ticketId, specialWorkType } = option
    this.nodeTaskId = nodeTaskId
    this.ticketId = ticketId
    this.workType = specialWorkType
    const res = await getCurrentInspectDetail(nodeTaskId)
    this.nodeInfo = res.data

    this.getAcceptanceConfig(specialWorkType)

    uni.setNavigationBarTitle({
      title: this.nodeInfo.nodeFormTitle || this.nodeInfo.nodeName
    })
    const dictReviewResult = []
    res.data.nodePermissions.forEach((item) => {
      item.optAlias = item.optAlias || item.permissionLabel
      dictReviewResult.push(item)
    })

    this.formData = {
      reviewDescription: '', // 验收意见说明
      reviewResult: actNodePermissionEnum.AGREE,
      targetNodeId: '',
      targetNodeName: '',
      candidateId: '',
      candidateName: '',
      reviewerSignatures: Number(res.data.nodeAllowMultiSign) === 1 ? [] : '',
      acceptanceInfo: {
        type: 1,
        acceptInfo: '',
        pictUrl: '',
        pictUrl1: '',
        pictUrl2: '',
        pictUrl3: '',
        otherDescription: '',
        ticketId: this.ticketId
      },
      acceptanceList: [],
      acceptanceFile: {
        acceptanceFile: '',
        safeCheckTable: '',
        otherFile: '',
        type: ''
      }
    }
    this.onResultChange(dictReviewResult.find((pet) => pet.permissionType === actNodePermissionEnum.AGREE))
    this.$refs.form.setRules(this.rules)
  },
  onReady() {
    this.$refs.form.setRules(this.rules)
  },
  computed: {
    allowMultiSign() {
      return Number(this.nodeInfo?.nodeAllowMultiSign)
    }
  },
  data() {
    return {
      specialWorkTypeEnum,
      acceptList: [
        {
          value: 1,
          label: '完工验收'
        },
        {
          value: 2,
          label: '未完工作业结束'
        }
      ],
      finishList: [],
      notfinishList: [],
      saveLoading: false,
      nodeInfo: {},
      ticketId: '',
      nodeTaskId: '',
      formData: {
        acceptanceInfo: {
          type: 1
        },
        acceptanceFile: {
          acceptanceFile: '',
          safeCheckTable: '',
          otherFile: '',
          type: ''
        }
      },
      workType: null,
      rules: {
        reviewDescription: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        'acceptanceInfo.otherDescription': {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        }
      }
    }
  },
  methods: {
    imageChange(urlList, field) {
      this.formData.acceptanceFile[field] = urlList.join(',')
    },
    changeFinish(data) {
      const checkValue = data.detail.data
      const dataArr = []
      checkValue.forEach((item) => {
        let findData = this.formData.acceptanceList.find((ite) => ite.acceptInfo === item.description)
        if (!findData) {
          dataArr.push({
            acceptInfo: item.description,
            pictUrl: '',
            ticketId: this.ticketId,
            type: 1
          })
        } else {
          dataArr.push(findData)
        }
      })
      this.formData.acceptanceList = dataArr
      this.formData.acceptanceInfo.acceptInfo
    },
    changeNotFinish(data) {
      if (data.dictValue != '其他原因"') {
        this.formData.acceptanceInfo.otherDescription = data.dictLabel
      } else {
        this.formData.acceptanceInfo.otherDescription = ''
      }
    },
    imageOnChange(urlList, item) {
      item.pictUrl = urlList.join(',')
    },
    getAcceptanceConfig(specialWorkType) {
      getAcceptanceConfig(specialWorkType).then((res) => {
        this.finishList = res.data
      })
    },
    getDicts() {
      getUnAcceptanceConfig().then((res) => {
        this.notfinishList = res.data
      })
    },
    async handleSubmit() {
      if (this.saveLoading) {
        return
      }
      if (!this.formData.acceptanceInfo.type) {
        this.$modal.showToast('请选择是否完工验收！')
        return
      } else {
        if (this.formData.acceptanceInfo.type === 1) {
          console.log(this.formData)
          if (this.formData.acceptanceInfo.acceptInfo.length === 0) {
            this.$modal.showToast('请勾选验收凭证！')
            return
          } else {
            let isHas = this.formData.acceptanceList.some(function (item) {
              return !item.pictUrl
            })
            if (isHas) {
              this.$modal.showToast('请上传对应验收凭证图片！')
              return
            }
          }
        } else {
          if (!this.formData.acceptanceInfo.acceptInfo) {
            this.$modal.showToast('请选择未完工作业结束的原因！')
            return
          }
        }
      }
      await this.$refs.form.validate()
      this.formData.acceptanceFile.type = this.formData.acceptanceInfo.type
      this.$refs.signature.open(this.nodeInfo.nodeTypeValue)
    },
    /**
     * @description  签名成功
     */
    async onSignatureSuccess() {
      this._save()
    },
    async _save(params = {}) {
      this.saveLoading = true
      if (this.formData.acceptanceInfo.type === 2) {
        this.formData.acceptanceList = []
        let obj = {
          type: this.formData.acceptanceInfo.type,
          ticketId: this.ticketId,
          pictUrl: '',
          acceptInfo: this.formData.acceptanceInfo.acceptInfo,
          otherDescription: this.formData.acceptanceInfo.otherDescription
        }
        this.formData.acceptanceList.push(obj)
      }
      try {
        await saveTicketInspect(this.nodeTaskId, {
          ...this.formData,
          ticketReviewContent: JSON.stringify(this.formData),
          ticketId: this.nodeInfo.ticketId,
          nodeId: this.nodeInfo.nodeId,
          nodeType: this.nodeInfo.nodeTypeValue,
          procInsId: this.nodeInfo.procInsId,
          nodeName: this.nodeInfo.nodeName,
          nodeTypeFlag: this.nodeInfo?.nodeTypeFlag,
          nodeTypeLabel: this.nodeInfo?.nodeTypeLabel,
          signatures: [
            {
              signatureType: signatureTypeEnum.OTHER,
              signatureUrls:
                Number(this.nodeInfo?.nodeAllowMultiSign) === 1
                  ? this.formData.reviewerSignatures.join(',')
                  : this.formData.reviewerSignatures
            }
          ]
        })
        this.$modal.showToast('验收成功')
        const eventChannel = this.getOpenerEventChannel()
        eventChannel.emit('callback:success', {
          data: true
        })
        uni.navigateBack()
      } catch (err) {
        this.saveLoading = false
      }
    },
    /**
     * 审核意见发生改变
     */
    onResultChange(val) {
      this.formData.reviewDescription = val?.defaultOpinion ?? ''
    }
  }
}
</script>

<style lang="scss" scoped>
.required__label {
  color: #a14430;
}

.submit_btn {
  padding: 0rpx 30rpx;
}
.page-view {
  padding-bottom: 60rpx;
}

.top-header {
  font-size: 26rpx;
  color: #999999;
  line-height: 80rpx;
  padding-left: 30rpx;
}

.signature-title {
  font-size: 30rpx;
  font-weight: 400;
  color: #333333;
  height: 80rpx;
  line-height: 80rpx;
}

.container {
  position: relative;

  .line {
    position: absolute;
    left: 55rpx;
    height: 100%;
    display: inline-block;
    width: 1rpx;
    background-color: #d5d7e3;
  }

  .add-wrap {
    background-color: #fff;
    background: #f8f8f8;
    border-radius: 39rpx;
    padding: 10rpx 20rpx;

    .icon {
      width: 32rpx;
      height: 32rpx;
      margin-right: 28rpx;
    }

    .no-data-text {
      line-height: 58rpx;
      font-size: 30rpx;
      color: #999999;
    }

    .button {
      line-height: 58rpx;
      background: #88b4c4;
      border-radius: 39rpx;
      font-size: 30rpx;
      color: #ffffff;
      padding: 0 30rpx;
    }
  }

  .card-wrap {
    position: relative;
    padding: 40rpx 30rpx 0 20rpx;
    display: flex;

    .number {
      width: 30rpx;
      height: 30rpx;
      line-height: 30rpx;
      background: #88b4c4;
      box-shadow: 0rpx 3rpx 6rpx 1rpx rgba(136, 180, 196, 0.5);
      border-radius: 50%;
      font-size: 24rpx;
      color: #ffffff;
      text-align: center;
      margin-left: 20rpx;
    }

    .content {
      margin-left: 28rpx;
      flex: 1;
      box-shadow: 0rpx 4rpx 10rpx 1rpx rgba(204, 204, 204, 0.5);
      border-radius: 10rpx;

      .header-wrap {
        background: #f1f6f9;
        display: flex;
        align-items: center;
        justify-content: space-between;
        line-height: 40rpx;
        padding: 20rpx 30rpx;

        .title {
          font-size: 30rpx;
          font-weight: 800;
          color: #333333;
        }

        .time {
          font-size: 26rpx;
          color: #999999;
        }
      }
    }
  }
}

.cu-card-wrap {
  margin: 0;
}

.text-area {
  height: 140rpx;
}

:deep(.uni-forms-item) {
  margin-bottom: 20rpx;
}

.popup-wrap {
  width: 650rpx;
  background: #fff;
  border-radius: 20rpx;
  padding: 20rpx 30rpx;

  .button-wrap {
    display: flex;
    justify-content: center;
    padding: 20rpx 0;

    .button {
      width: 246rpx;
      line-height: 88rpx;
      border-radius: 44rpx;
      text-align: center;
    }

    .button-confirm {
      background: #454a5e;
      color: #ffffff;
      margin-right: 29rpx;
    }

    .button-cancle {
      background: #e3e4eb;
      color: #454a5e;
      margin-left: 29rpx;
    }
  }
}

.hidden-title {
  background: #f5f5f5;
  padding: 20rpx 30rpx;
  color: #999;
}

.button-confirm {
  margin: 40rpx auto 0;
  width: 600rpx;
  line-height: 98rpx;
  background: #454a5e;
  border-radius: 50rpx;
  font-size: 36rpx;
  color: #ffffff;
  text-align: center;
}

//
::v-deep .uni-table-loading {
  display: none;
}

.input__cls {
  display: inline-block;
  width: 100rpx;
  vertical-align: sub;
  font-size: 28rpx;
  color: #333333;
  text-align: center;
  border-bottom: 1rpx solid #333333;
}
</style>
